package com.xjtu.chapter09;

import java.util.*;

/**
 * @author yjq
 * @version 1.0
 * @date 2021/9/3 22:01
 */
public class SetTest {
    public static void main(String[] args) {
        //过滤重复元素，但是不保证元素的迭代次序
        String[] strArray = new String[]{"one","world","one","dream"};
        Set<String> s = new HashSet<String>();
        for (int i = 0; i <4 ; i++) {
            if(!s.add(strArray[i])){
                //添加strArray元素到集合s中
                System.out.println("Duplicate detected: "+strArray[i]);
            }
        }
        System.out.println(s.size()+" distinct words: "+s);

        //自动按照升序排列内容，并过滤重复元素
        TreeSet<String> treeSet = new TreeSet<>();
        treeSet.add("b");
        treeSet.add("a");
        treeSet.add("c");
        treeSet.add("d");
        treeSet.add("b");
        System.out.println("TreeSet:");
        System.out.println(treeSet);
        System.out.println("the first element is: "+treeSet.first());
        //返回第一个元素
        Iterator<String>iterator = treeSet.iterator();//迭代器
        while(iterator.hasNext()){
            System.out.println(iterator.next()+";");
        }

        //过滤重复元素，不保证元素的迭代次序
        LinkedHashSet<String> hashSet =new LinkedHashSet<>();
        hashSet.add("b");
        hashSet.add("a");
        hashSet.add("c");
        hashSet.add("d");
        hashSet.add("b");
        System.out.println("LinkedHashSet: ");
        System.out.println(hashSet);
        Iterator<String> iterator1 = hashSet.iterator();
        while(iterator1.hasNext()){
            System.out.println(iterator1.next()+";");
        }
    }
}
